package com.itheima.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 获取token，拦截非登录用户
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头的token
        String token = request.getHeader("Authorization");

        //2.判断token是否为空
        if (StrUtil.isBlank(token)) {
            response.sendError(401);
            return false;
        }

        //3.处理token
        token = token.replace("Bearer ","");

        //5.通过token获取redis中的数据
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        if (StrUtil.isBlank(json)) {
            response.sendError(401);
            return false;
        }

        //6.若能获取到,转成admin
        Admin admin = null;
        try {
            admin = JSON.parseObject(json, Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(401);
            return false;
        }

        //7.将admin绑定当前线程
        AdminHolder.set(admin);

        //8.token续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token,json, Duration.ofHours(1));

        //9、放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}